const http = require('http');
const fs = require('fs');
const path = require('path');
const resolve = filepath => path.join(__dirname, filepath);
let options = {
  hostname: 'localhost'
  , port: 3000
  , path: '/'
  , method: 'GET'
};

let ws = fs.createWriteStream(resolve('download.txt'));
let pause = false;
let start = 0;
let N = 10; //每次请求的字节数总量

// 下载 每次获取10个字节
function download(){
  options.headers = {
    Range: `bytes=${start}-${start + N - 1}` //因为这里是又包后的 我们这里只期望一次接受10个字节
  };

  /*let req = http.request()
  req.end();*/

  //等价于上面两行，好处在于不再需要调end

  http.get(options, function (res) {
    const range = res.headers['content-range']; //服务器返回的头，其值为发送回来的数据段的编号，以及总大小
    const total = range.split('/')[1];
    const buffers = [];
    res.on('data', (chunk) => {
      buffers.push(chunk);
    });
    res.on('end', () => {
      ws.write(Buffer.concat(buffers));
      start += N; //确认写入后再维护
      setTimeout(() => {
        if (pause === false && start < total) {
          download();
        }else if (start > total) {
          process.exit();
        }
      }, 2000);
    });
  });
}

process.stdin.on('data', (chunk) => {
  const option = chunk.slice(0, chunk.length - 2 /*0a←回车*/).toString();
  console.log('chunk:',chunk);
  console.log('option:',option);
  switch (option) {
    case 'p':
      console.log('已暂停');
      pause = true;
      break;
    case 's':
      console.log('已停止下载');
      process.exit();
      break;
    case 'r':
      console.log('已恢复下载');
      pause = false;
      download();
      break;
    default:
      if (/^n\s-[0-9]+$/.test(option)) {
        const newN = option.slice(3);
        console.log(`每次请求的字节数变更为${newN}`);
        N = parseInt(newN);
      }
      break;
  }
});

download();
